package com.shuoyue.ycgk.ui.course.info;

import android.animation.ValueAnimator;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.base.baseadapter.IndexFragmentAdapter;
import com.shuoyue.ycgk.entity.Course;
import com.shuoyue.ycgk.entity.CourseInfo;
import com.shuoyue.ycgk.entity.TimerTable;
import com.shuoyue.ycgk.ui.common.CollectContract;
import com.shuoyue.ycgk.ui.course.adapter.TeacherAdapter;
import com.shuoyue.ycgk.ui.course.contract.CourseContract;
import com.shuoyue.ycgk.utils.HorizontalSpacesItemDecoration;
import com.shuoyue.ycgk.utils.SizeUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 课程详情
 */
public class CourseInfoActivityBackup extends BaseMvpActivity<CourseContract.Presenter> implements CourseContract.CourseListView, CollectContract.View {
    CourseInfo course;
    List<BaseMvpFragment> fragmentList = new ArrayList<>();
    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.time_count)
    TextView timeCount;
    @BindView(R.id.learn_count)
    TextView learnCount;
    @BindView(R.id.lay_top)
    LinearLayout layTop;
    @BindView(R.id.line_spe)
    View lineSpe;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.lay_pager)
    LinearLayout layPager;
    @BindView(R.id.price_bt)
    TextView priceBt;
    @BindView(R.id.buy)
    Button buy;
    @BindView(R.id.teachersRecycleView)
    RecyclerView teachersRecycleView;
    @BindView(R.id.lay_bottom)
    LinearLayout layBottom;
    //设置手势识别监听器;转换方式
    boolean isAtTop = false;
    public GestureDetector gesture; //手势识别

    TeacherAdapter teacherAdapter;
    IndexFragmentAdapter indexFragmentAdapter;

    CollectContract.Presenter collectPresenter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_course_info;
    }

    @Override
    protected void initView() {
        this.pageTitle.setText("课程详情");
        gesture = new GestureDetector(mContext, new MyOnGestureListener());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        teachersRecycleView.setLayoutManager(linearLayoutManager);
        teachersRecycleView.addItemDecoration(new HorizontalSpacesItemDecoration(SizeUtil.dip2px(mContext, 8), false));
        teacherAdapter = new TeacherAdapter(null);
        teachersRecycleView.setAdapter(teacherAdapter);
    }

    void setCourseData(CourseInfo course) {
        title.setText(course.getProduct().getName());
        if (course.getProduct().getDefaultPrice() != null) {
            price.setText("￥" + course.getProduct().getDefaultPrice().getPrice());
            priceBt.setText("￥" + course.getProduct().getDefaultPrice().getPrice());
        } else {
            price.setText("免费");
//            layBottom.setVisibility(View.GONE);
            buy.setText("收藏课程");
        }
        Glide.with(mContext).load(course.getProduct().getCover()).error(R.mipmap.img_loading_gray).into(img);
        timeCount.setText(course.getProduct().getAmount() + "课时");
        learnCount.setText("已有" + course.getProduct().getSalesVolume() + "学习");
        indexFragmentAdapter = new IndexFragmentAdapter(getSupportFragmentManager(), fragmentList);
        fragmentList.add(FragmentCourseInfo.newInstance(course.getProduct().getIntroduce()));
        fragmentList.add(FragmentCourseTimetable.newInstance(course.getCourseArrangementList(),
                course.getProduct(),course.getIsPay()));
        if (course.getCourseDatas() != null && course.getCourseDatas().size() > 0)
            fragmentList.add(FragmentCourseTeacher.newInstance(course.getTeacherList()));
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(indexFragmentAdapter);
        viewPager.setCurrentItem(0);
        teacherAdapter.resetData(course.getTeacherList());
    }

    @OnClick({R.id.back, R.id.buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.buy:
                if (course.getProduct().getDefaultPrice() != null) {
                    //收藏
                    collectPresenter.saveCollect(course.getProduct().getId(), 2);
                } else {

                }
                break;
        }
    }

    @Override
    public void initData() {
        collectPresenter = new CollectContract.Presenter();
        collectPresenter.attachView(this);
        mPresenter = new CourseContract.Presenter();
        mPresenter.attachView(this);
        mPresenter.getCourseInfo(getIntent().getIntExtra("id", -1));
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        gesture.onTouchEvent(event);
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void setCourseList(ListWithPage<Course> list) {

    }

    @Override
    public void setCourseInfo(CourseInfo info) {
        this.course = info;
        setCourseData(course);
    }

    @Override
    public void setVideoInfo(TimerTable timerTable,TimerTable adapterData) {

    }

    @Override
    public void notBuyNotice() {

    }

    @Override
    public void addCollectSuc() {

    }

    @Override
    public void deleteCollectSuc() {

    }


    private class MyOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (Math.abs(velocityX) > Math.abs(velocityY)) {
                //横向不操作
                return false;
            }
            boolean isChildAtTop = ((BaseCourseInfoFragment) indexFragmentAdapter.getCurrentFragment()).isScrollAtTop;
            if (velocityY < 0) {
                //向上不拦截优先推父控件
                if (!isAtTop) {
                    startAnimation(2);
                    return true;
                } else {
                    return false;
                }
            } else {
                //向下判断子元素是否在顶部,在顶部则滑动父元素
                //否则交给子元素操作
                if (isChildAtTop && isAtTop) {
                    startAnimation(1);
                    return true;
                }
                return false;
            }
        }
    }


    private void resetLocation(int marginTop, int pagerHeight) {
//        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) layPager.getLayoutParams();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layPager.getLayoutParams();
        layoutParams.setMargins(0, marginTop, 0, 0);
        layPager.setLayoutParams(layoutParams);
        //                //Viewpager 设置高度属性
        LinearLayout.LayoutParams layoutParamsPager = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pagerHeight);
        viewPager.setLayoutParams(layoutParamsPager);
    }

    /**
     * 动画效果的取值
     *
     * @param derection 方向:1向↓,2向↑
     */
    public void startAnimation(int derection) {
        isAtTop = derection == 2;
        //计算距离
        int toplayHeight = layTop.getHeight();//向上距离空间
        int maxPagerHeight = SizeUtil.getLocationH(layBottom) - SizeUtil.getLocationH(layTop) - tabLayout.getHeight();//pager 最大高度
        ValueAnimator animator = ValueAnimator.ofInt(derection == 1 ? 0 - toplayHeight : 0, derection == 1 ? 0 : 0 - toplayHeight);
        animator.setDuration(300).start();
        animator.setInterpolator(new AccelerateInterpolator());
        animator.addUpdateListener(animation -> {
            //重置
            int anmationValue = (Integer) animation.getAnimatedValue();
            resetLocation(anmationValue, maxPagerHeight - anmationValue);
        });
    }
}
